-- ========================================================
-- @File	: error.lua
-- @Brief	: 默认的错误处理controller
-- @Author	: Leo Zhao
-- @Date	: 2016-05-05
-- ========================================================
error_handler = error_handler or {}

-- 非法网址（404）
function error_handler.empty()
	if _CONF and _CONF.error_handler and _CONF.error_handler.empty then
		return _CONF.error_handler.empty();
	end
	
	local render = require 'core.template';
	header("Content-type:text/html");

	local html = [[	
	{(public/header.html)}
		<div class="container">
			<h1 style="font-size:4em; font-weight:bold; text-align:center; margin-top:5%"> ERR 404 </h1><br>
			<div class="alert alert-danger" role="alert" style="text-align:center;"><h3><b>:( OOPS PAGE NOT EXISTS.</b></h3></div>					
		</div>
	{(public/footer.html)}
	]];

	render.render(html, { title = "页面不存在" });
end

-- 内部错误（500）
function error_handler.fatal(err)
	if _CONF and _CONF.error_handler and _CONF.error_handler.fatal then
		return _CONF.error_handler.fatal(err);
	end

	local is_develop = _CONF.develop;
	local render = require 'core.template';
	local stack = debug.traceback();

	log.error(err .. "\n" .. stack);
	header("Content-type:text/html");

	if is_develop then
		local html = [[
		{(public/header.html)}
			<div class="container">
				<h1 style="font-size:4em; font-weight:bold; text-align:center; margin-top:5%">GOT AN ERROR</h1><br>

				<div class="card">
					<div class="card-header"><strong class="text-danger">{{err}}</strong></div>
					<div class="card-block"><i>{*stack*}</i></div>
				</div>

				<h4>Information : </h4>
				<table class="table table-bordered">
					<tr>
						<td width="100"><b>uri</b></td><td>{{_URL}}</td>
					</tr>
					<tr>
						<td width="100"><b>method</b></td><td>{{_METHOD}}</td>
					</tr>
					<tr>
						<td width="100"><b>param_get</b></td><td>{{_GET_ORG}}</td>
					</tr>
					<tr>
						<td width="100"><b>param_post</b></td><td>{{_POST_ORG}}</td>
					</tr>
					<tr>
						<td width="100"><b>remote</b></td><td>{{_REMOTE}}</td>
					</tr>
					<tr>
						<td width="100"><b>session</b></td><td>{% data = store.get(session.id()); %}{*data*}</td>
					</tr>
				</ul>
			</div>
		{(public/footer.html)}
		]];

		render.render(html, {
			title = "出错了",
			err = err,
			stack = string.gsub(stack, "\n", "<br>")
		});
	else
		local html = [[	
		{(public/header.html)}
			<div class="container">
				<h1 style="font-size:4em; font-weight:bold; text-align:center; margin-top:5%"> ERR 404 </h1><br>
				<div class="alert alert-danger" role="alert" style="text-align:center;"><h3><b>:( OOPS PAGE NOT EXISTS.</b></h3></div>					
			</div>
		{(public/footer.html)}
		]];

		render.render(html, { title = "页面不存在" });
	end
end